package com.hotcars.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.hotcars.model.Car;

public class CarDao {
	private Connection con;
	private Statement stmt;
	private ResultSet rs;
	
	public List<Car> getCars() {
		try {
			List<Car> cars = new ArrayList<Car>();
			Class.forName("com.mysql.jdbc.Driver");
			// Creating our connection
			con = DriverManager.getConnection("jdbc:mysql://localhost/hotcars_db", "root", "");
			stmt = con.createStatement();
			rs = stmt.executeQuery("SELECT * FROM CARS ORDER BY ID DESC");			
			while (rs.next()) {
				Car car = new Car();
				car.setId(rs.getInt("ID"));
				car.setVin(rs.getString("VIN"));
				car.setMake(rs.getString("MAKE"));
				car.setModel(rs.getString("MODEL"));
				car.setYear(rs.getInt("YEAR"));
				car.setPrice(rs.getFloat("PRICE"));	
				car.setMileage(rs.getInt("MILEAGE"));
				car.setEngine(rs.getString("ENGINE"));
				car.setTransmission(rs.getString("TRANSMISSION")); 
				car.setBodyStyle(rs.getString("BODY_STYLE"));
				car.setExterior(rs.getString("EXTERIOR"));
				car.setInterior(rs.getString("INTERIOR"));
				
				cars.add(car);
			}
			close();
			return cars;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public Car getCar(int id)  {
		Car car = new Car();
		try {
			// Creating our connection
			con = DriverManager.getConnection("jdbc:mysql://localhost/hotcars_db", "root", "");
			stmt = con.createStatement();
			rs = stmt.executeQuery("SELECT * FROM CARS WHERE ID = " + id);			
			while (rs.next()) {
				car.setId(rs.getInt("ID"));
				car.setVin(rs.getString("VIN"));
				car.setMake(rs.getString("MAKE"));
				car.setModel(rs.getString("MODEL"));
				car.setYear(rs.getInt("YEAR"));
				car.setPrice(rs.getFloat("PRICE"));	
				car.setMileage(rs.getInt("MILEAGE"));
				car.setEngine(rs.getString("ENGINE"));
				car.setTransmission(rs.getString("TRANSMISSION")); 
				car.setBodyStyle(rs.getString("BODY_STYLE"));
				car.setExterior(rs.getString("EXTERIOR"));
				car.setInterior(rs.getString("INTERIOR"));					
			}
			close();
			return car;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private void close() {
		try {
			if (rs != null) {
				rs.close();
			}

			if (stmt != null) {
				stmt.close();
			}

			if (con != null) {
				con.close();
			}
		} catch (Exception e) {

		}
	}

}
